<?php
/***
 * Candy框架 框架会话控制Session类
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2019-07-26 11:31:47 $   
 */
 
declare(strict_types=1);
namespace Candy\Extend\Cache;

defined('CANDY') OR die('You Are A Bad Guy. o_O???');
 
final Class CacheSession {
	private static $handler=null;
	private static $lifetime=null;
	
	/**
	 * 初使化和开启session
	 *
	 * @param	$cacheobj	cache对象
	 */
	public static function start(object $cacheobj,string $sessionid = null): bool
	{
		if(!defined('SECACHE')){
			if(session_status() === PHP_SESSION_ACTIVE){
				session_destroy();
			}
			
			//开启标注
			define('SECACHE', true);
			//不使用 GET/POST 变量方式
			//ini_set('session.use_trans_sid',    0);
			//设置垃圾回收最大生存时间
			//ini_set('session.gc_maxlifetime',  3600);
			//使用 COOKIE 保存 SESSION ID 的方式
			//ini_set('session.use_cookies',      1);
			//ini_set('session.cookie_path',      '/');
			//多主机共享保存 SESSION ID 的 COOKIE
			//ini_set('session.cookie_domain','.candycms.cn');
			self::$handler = $cacheobj;
			self::$lifetime = ini_get('session.gc_maxlifetime');
			session_set_save_handler(
				[__CLASS__, 'open'],
				[__CLASS__, 'close'],
				[__CLASS__, 'read'],
				[__CLASS__, 'write'],
				[__CLASS__, 'destroy'],
				[__CLASS__, 'gc']
			);
		}
		
		if(!is_null($sessionid)){
			session_id($sessionid);
		}
		session_start();
		return true;
	}
	
	public static function open(string $path,string $name): bool
	{
		return true;
	}
	
	public static function close(): bool
	{
		return true;
	}

	/**
	 * 从SESSION中读取数据
	 *
	 * @param	string	$PHPSESSID	session的ID
	 * @return 	mixed  返回session中对应的数据
	 */
	public static function read(string $PHPSESSID): string
	{
		$out=self::$handler->get(self::session_key($PHPSESSID));
		if($out===false || $out == null)
			return '';
		return $out;
	}

	/**
	 *向session中添加数据
	 */
	public static function write(string $PHPSESSID, $data): bool
	{
		return self::$handler->set(self::session_key($PHPSESSID), $data);
	}

	public static function destroy(string $PHPSESSID): bool
	{
		return self::$handler->delete(self::session_key($PHPSESSID));
	}

	public static function gc(int $lifetime):bool
	{
		//无需额外回收,memcache有自己的过期回收机制
		return true;
	}
	
	public function instance(): CacheSession
	{
		return self::class;
	}
	
	public function __call(string $name,array $arguments = [])
	{
		switch($name){
			case 'close':
				return self::close();
			case 'read':
			case 'destroy':
			case 'gc':
				return self::$name($arguments[0]);
			case 'open':
			case 'write':
				return self::$name($arguments[0], $arguments[1]);
		}
	}

	private static function session_key(string $PHPSESSID): string
	{
		$session_key = G('TABPREFIX') . $PHPSESSID;
		return $session_key;
	}
}
